package com.salt.security.filter;

import com.salt.security.BaseUserDetails;
import com.salt.security.UserDetailsServiceImpl;
import com.salt.security.jwt.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * jwt过滤器
 *
 * @author HaiBo Kuang
 */
@Component
public class JwtRequestFilter extends OncePerRequestFilter {
    private final Logger log = LoggerFactory.getLogger("Jwt_Request_Filter");
    private JwtUtil jwtUtil;
    private UserDetailsService userDetailsService;

    @Autowired
    public void setJwtRequestFilter(JwtUtil jwtUtil, UserDetailsServiceImpl userDetailsService) {
        this.jwtUtil = jwtUtil;
        this.userDetailsService = userDetailsService;
    }

    /**
     * 与doFilter作用相同，但保证在单个请求线程中每个请求仅被调用一次。
     *
     * @param request  http请求
     * @param response http响应
     * @param chain    过滤链
     * @throws ServletException ServletException
     * @throws IOException      IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    @NonNull HttpServletResponse response,
                                    @NonNull FilterChain chain)
            throws ServletException, IOException {

        log.info("jwt filter 工作...");
        // 请求头获取token
        final String authorization = request.getHeader("Authorization");

        String username = null;
        String jwt = null;
        // bearer token前缀
        final String bearerPrefix = "Bearer ";
        if (authorization != null && authorization.startsWith(bearerPrefix)) {
            jwt = authorization.substring(bearerPrefix.length());
            // 解析用户名
            username = jwtUtil.extractUsername(jwt);
        }
        if (Objects.nonNull(username) && Objects.isNull(SecurityContextHolder.getContext().getAuthentication())) {
            // 加载用户信息
            log.info("<==加载用户名为：{}，的用户信息==>", username);
            BaseUserDetails userDetails = (BaseUserDetails) userDetailsService.loadUserByUsername(username);
            if (jwtUtil.validateToken(jwt, userDetails)) {
                log.info("<==当前token验证成功==>");
                log.info("<==当前用户权限:{}==>", userDetails.getAuthorities().toString());
                // jwt拦截后，取用户信息 设置用户认证信息
                UsernamePasswordAuthenticationToken token
                        = new UsernamePasswordAuthenticationToken(userDetails, null,
                        userDetails.getAuthorities());
                WebAuthenticationDetails details = new WebAuthenticationDetailsSource().
                        buildDetails(request);
                token.setDetails(details);
                // 设置认证信息到SpringSecurity上下文
                SecurityContextHolder.getContext().setAuthentication(token);
            }
        }
        chain.doFilter(request, response);
    }
}
